//
//  shareDimensionalView.m
//  QRMaster
//
//  Created by myApple on 15/7/25.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "shareDimensionalView.h"
#import "PromptInfoView.h"
#import "InternationalControl.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>

@interface shareDimensionalView()<UITextFieldDelegate,ABPeoplePickerNavigationControllerDelegate>
{
    UIDatePicker * selectPickView;
    UITextField * beginTextField;
    UITextField * endTextField;
    NSString * dateString;
    NSString * timeString;
    
    UIButton * dateBtn;
    UIButton * timeBtn;
    
    NSDate * lastDate;//最多可以分享的时间
    
    NSMutableArray * postArray;//上传信息参数
    
    NSInteger secs;//算出九十天后的日期
    NSInteger shareSecs;//算出三十天后的日期
    //多语言
    UILabel * beginDateTimeLabel;
    UILabel * endDateTimeLabel;
    UIButton * makeSureBtn;
    NSString * localString;
}

@end


@implementation shareDimensionalView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = RGBA(237, 238, 241, 1);
        secs = 90 * 24 * 3600;
        shareSecs = 30 * 24 * 3600;
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeLanguage) name:@"changeLanguage"object:nil];
        if ([[InternationalControl userLanguage]isEqualToString:@"en"]) {
            localString = @"en_US";
        }
        else if ([[InternationalControl userLanguage]isEqualToString:@"zh-Hans"])
        {
            localString = @"zh_CN";
        }
        else
        {
            localString = @"zh-Hant";
        }
        [self prepareTitleView];
        [self prepareDateTimePickView];
    }
    return self;
}
-(void)changeLanguage
{
    beginDateTimeLabel.text = NSLocalizedString(@"beginTime", nil);
    beginTextField.placeholder = NSLocalizedString(@"chooseBeginTime", nil);
    endDateTimeLabel.text = NSLocalizedString(@"endTime", nil);
    endTextField.placeholder = NSLocalizedString(@"chooseEndTime", nil);
    [makeSureBtn setTitle:NSLocalizedString(@"alterSure", nil) forState:0];
}

-(void)prepareTitleView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float x = 10;
    float y = 20;
    float width = 70;
    float height = 20;
    
    beginDateTimeLabel =[[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    beginDateTimeLabel.text = NSLocalizedString(@"beginTime", nil);
    beginDateTimeLabel.font = [UIFont systemFontOfSize:14.0];
    [self addSubview:beginDateTimeLabel];
    
    x += width;
    width = ScreenWidth - x - 10;
    y -= 10;
    height = 40;
    beginTextField =[[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    beginTextField.borderStyle = UITextBorderStyleRoundedRect;
    beginTextField.placeholder = NSLocalizedString(@"chooseBeginTime", nil);
    beginTextField.delegate = self;
    beginTextField.inputView = [[UIView alloc]init];//不弹起键盘
    [self addSubview:beginTextField];
    
    //结束时间
    x = 10;
    y += height + 15;
    height = 20;
    width = 70;
    endDateTimeLabel =[[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    endDateTimeLabel.text = NSLocalizedString(@"endTime", nil);
    endDateTimeLabel.font = [UIFont systemFontOfSize:14.0];
    [self addSubview:endDateTimeLabel];
    
    x += width;
    width = ScreenWidth - x - 10;
    y -= 10;
    height = 40;
    endTextField =[[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    endTextField.borderStyle = UITextBorderStyleRoundedRect;
    endTextField.placeholder = NSLocalizedString(@"chooseEndTime", nil);
    endTextField.delegate = self;
    endTextField.inputView = [[UIView alloc]init];
    [self addSubview:endTextField];
}

#pragma mark -- 准备时间试图
-(void)prepareDateTimePickView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float x = 10;
    float y = endTextField.frame.size.height + endTextField.frame.origin.y + 10;
    float width = ScreenWidth - 2 * 10;
    float height = 256;
    
    UIView * backView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    backView.layer.borderColor = RGBA(125, 194, 52, 1).CGColor;
    backView.layer.borderWidth = 1.0;
    backView.layer.cornerRadius = 5;
    backView.layer.masksToBounds = YES;
    [self addSubview:backView];
    
    x = 0;
    y = 0;
    width = backView.frame.size.width / 2.0;
    height = 30;
    dateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    dateBtn.frame = CGRectMake(x, y, width, height);
    [dateBtn setTitleColor:[UIColor blackColor] forState:0];
    [dateBtn setBackgroundColor:[UIColor colorWithRed:125/255.0 green:194/255.0 blue:52/255.0 alpha:0.18]];
    [dateBtn addTarget:self action:@selector(selectDate:) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:dateBtn];
    
    UIView * dateLineView = [[UIView alloc]initWithFrame:CGRectMake(width, y, 1, height)];
    dateLineView.backgroundColor = RGBA(125, 194, 52, 1);
    [backView addSubview:dateLineView];
    
    x += width - 1;
    timeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    timeBtn.frame = CGRectMake(x, y, width, height);
    [timeBtn setTitleColor:[UIColor blackColor] forState:0];
    [timeBtn addTarget:self action:@selector(selectTime:) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:timeBtn];
    
    UIView * timeLineView = [[UIView alloc]initWithFrame:CGRectMake(0, height, backView.frame.size.width, 1)];
    timeLineView.backgroundColor = RGBA(125, 194, 52, 1);
    [backView addSubview:timeLineView];
    
    x = 0;
    y += height - 5;
    width = backView.frame.size.width;
    height = 196;
    selectPickView = [[UIDatePicker alloc]initWithFrame:CGRectMake(x, y, width, height)];
    selectPickView.datePickerMode = UIDatePickerModeDate;
    [selectPickView addTarget:self action:@selector(selectDateTime:) forControlEvents:UIControlEventValueChanged];
    [backView addSubview:selectPickView];
    
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0.0];
    NSDate * endDate = [NSDate dateWithTimeIntervalSinceNow:secs];
    // 打印日期：中间的空格可以用'at'或'T'等字符来分隔
    NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
    [dateFomatter setDateFormat:@"yyyy-MM-dd"];
    [dateFomatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:localString]];
    [dateFomatter stringFromDate:date];
    [dateFomatter stringFromDate:endDate];
    dateString = [dateFomatter stringFromDate:date];
    [dateBtn setTitle:dateString forState:0];
    selectPickView.minimumDate = date;
    selectPickView.maximumDate = endDate;
    lastDate = endDate;
    
    [dateFomatter setDateFormat:@"HH:mm"];
    timeString = [dateFomatter stringFromDate:date];
    [timeBtn setTitle:timeString forState:0];
    
    x = 0;
    width = backView.frame.size.width;
    y += height - 5;
    height = 40;
    makeSureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    makeSureBtn.frame = CGRectMake(x, y, width, height);
    [makeSureBtn setTitle:NSLocalizedString(@"alterSure", nil) forState:0];
    [makeSureBtn setTitleColor:RGBA(135, 199, 66, 1) forState:0];
    makeSureBtn.layer.cornerRadius = 5;
    makeSureBtn.layer.masksToBounds = YES;
    makeSureBtn.layer.borderWidth = 1.0;
    makeSureBtn.layer.borderColor = RGBA(125, 194, 52, 1).CGColor;
    [makeSureBtn addTarget:self action:@selector(makeSure:) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:makeSureBtn];
}

-(void)selectDateTime:(UIDatePicker *)pickView
{
    NSDateFormatter * df = [NSDateFormatter new];
    [df setDateFormat:@"yyyy-MM-dd"];
    [df setLocale:[[NSLocale alloc]initWithLocaleIdentifier:localString]];
    if (pickView.datePickerMode == UIDatePickerModeDate) {
        dateString = [df stringFromDate:pickView.date];
        [dateBtn setTitle:dateString forState:0];
    }
    else
    {
        [df setDateFormat:@"HH:mm"];
        timeString = [df stringFromDate:pickView.date];
        [timeBtn setTitle:timeString forState:0];
    }
}

-(void)selectDate:(UIButton *)btn
{
    [timeBtn setBackgroundColor:[UIColor clearColor]];
    [dateBtn setBackgroundColor:[UIColor colorWithRed:125/255.0 green:194/255.0 blue:52/255.0 alpha:0.18]];
    selectPickView.datePickerMode = UIDatePickerModeDate;
    if ([endTextField isEditing]) {
        selectPickView.datePickerMode = UIDatePickerModeDate;
        NSDateFormatter * df = [NSDateFormatter new];
        [df setDateFormat:@"yyyy-MM-dd"];
        [df setLocale:[[NSLocale alloc]initWithLocaleIdentifier:localString]];
        selectPickView.minimumDate = [df dateFromString:dateString];
        [timeBtn setTitle:timeString forState:0];
    }
    else
    {
        NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0.0];
        // 打印日期：中间的空格可以用'at'或'T'等字符来分隔
        NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
        [dateFomatter setDateFormat:@"yyyy-MM-dd"];
        [dateFomatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:localString]];
        [dateFomatter stringFromDate:date];
        selectPickView.minimumDate = date;
        [timeBtn setTitle:timeString forState:0];
    }
    
    
}

-(void)selectTime:(UIButton *)btn
{
    [dateBtn setBackgroundColor:[UIColor clearColor]];
    [timeBtn setBackgroundColor:[UIColor colorWithRed:125/255.0 green:194/255.0 blue:52/255.0 alpha:0.18]];
    selectPickView.datePickerMode = UIDatePickerModeCountDownTimer;
    if ([endTextField isEditing]) {
        NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
        [dateFomatter setDateFormat:@"HH:mm"];
        [dateFomatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:localString]];
        selectPickView.minimumDate =[dateFomatter dateFromString:timeString];
    }
    [dateBtn setTitle:dateString forState:0];
}

-(void)makeSure:(UIButton *)btn
{
    if (beginTextField.editing) {
        beginTextField.text = [NSString stringWithFormat:@"%@ %@",dateString,timeString];
        if(_delegate && [_delegate respondsToSelector:@selector(shareDimensionaViewSendTime:typeTime:)])
        {
            [_delegate shareDimensionaViewSendTime:beginTextField.text typeTime:NO];
            [endTextField becomeFirstResponder];
        }
        //此时如果开始时间与结束时间超过一个月则把结束时间修改成开始时间的后一天
        if (![endTextField.text isEqualToString:@""]) {
            [self compareBegin:beginTextField.text to:endTextField.text];
        }
        //设置最大时间，如果最大时间大于lastdate则就是lastdate
        [self setMaxDateforPickView:dateString];
        
    }
    else if(endTextField.editing)
    {
        NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
        [dateFomatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        [dateFomatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:localString]];
        
        NSComparisonResult result = [[dateFomatter dateFromString:beginTextField.text] compare:[dateFomatter dateFromString:[NSString stringWithFormat:@"%@ %@",dateString,timeString]]];
        if (result == NSOrderedAscending || result == NSOrderedSame) {
            endTextField.text = [NSString stringWithFormat:@"%@ %@",dateString,timeString];
            if(_delegate && [_delegate respondsToSelector:@selector(shareDimensionaViewSendTime:typeTime:)])
            {
                [_delegate shareDimensionaViewSendTime:endTextField.text typeTime:YES ];
                
            }
        }
        else
        {
            [PromptInfoView showMessage:NSLocalizedString(@"timeErrorChoose", nil) superView:self];
        }
    }
    
}


#pragma mark -----------  结束时间小于开始时间 结束时间大于开始时间的三十天
-(BOOL)compareBegin:(NSString *)begin to:(NSString *)end
{
    NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
    [dateFomatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    [dateFomatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:localString]];
    NSDate * beginDate = [dateFomatter dateFromString:begin];
    NSDate * newBeginDate = [NSDate dateWithTimeInterval:shareSecs sinceDate:beginDate];
    NSDate * endDate = [dateFomatter dateFromString:end];
    
    if ([self dateCompare:beginDate to:endDate]) {
        //开始时间大于等于结束时间
         endDate = [NSDate dateWithTimeInterval:24 * 3600 sinceDate:beginDate];
        if ([self dateCompare:endDate to:lastDate]) {
            //结束时间大于最终时间
            endDate = lastDate;
        }
    }
     else
     {
         //开始时间小于结束时间
         if (![self dateCompare:newBeginDate to:endDate]) {
             //结束时间比开始时间大于三十天
              endDate = [NSDate dateWithTimeInterval:24 * 3600 sinceDate:beginDate];
         }
     }
    endTextField.text = [dateFomatter stringFromDate:endDate];
    if(_delegate && [_delegate respondsToSelector:@selector(shareDimensionaViewSendTime:typeTime:)])
    {
        [_delegate shareDimensionaViewSendTime:endTextField.text typeTime:YES ];
        
    }
    
    return YES;
}

#pragma mark ---- 单纯的两个时间的比较 开始时间大于或者等于结束时间为yes  否则为no
-(BOOL)dateCompare:(NSDate *)beginDate to:(NSDate *)endDate
{
    NSComparisonResult result = [beginDate compare:endDate];
    if (result == NSOrderedDescending || result == NSOrderedSame) {
        return YES;
    }
    else
    {
         return NO;
    }
   
}

#pragma mark -------- 设置可以选择的最大日期
-(void)setMaxDateforPickView:(NSString *)string
{
    NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
    [dateFomatter setDateFormat:@"yyyy-MM-dd"];
    [dateFomatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:localString]];
    NSDate * beginDate = [dateFomatter dateFromString:string];
    NSDate * endDate = [NSDate dateWithTimeInterval:shareSecs sinceDate:beginDate];
    
    if ([self dateCompare:endDate to:lastDate]) {
        endDate = lastDate;
    }
    selectPickView.maximumDate = endDate;
    [selectPickView reloadInputViews];
}

#pragma mark ---------textfiledDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == beginTextField) {
        NSDate * endDate = [NSDate dateWithTimeIntervalSinceNow:secs];
        selectPickView.maximumDate = endDate;
        [selectPickView reloadInputViews];
    }
    else
    {
        [self setMaxDateforPickView:dateString];
    }
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
